#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    scene = new MyScene();
    ui->graphicsView->setScene(scene);

    connect(scene,SIGNAL(mouseClicked(QGraphicsSceneMouseEvent*)),this,SLOT(graphicsViewMouseClicked(QGraphicsSceneMouseEvent*)));
    scene->setSceneRect(-100000,-100000,100000,100000);
    ui->graphicsView->centerOn(ui->graphicsView->mapToScene(0,0));
    ui->graphicsView->setBackgroundBrush(Qt::black);
    ui->graphicsView->horizontalScrollBar()->setValue(-50000);
    ui->graphicsView->verticalScrollBar()->setValue(-50000);
    toolType = SELECT;

    scale = 1;
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::graphicsViewMouseClicked(QGraphicsSceneMouseEvent *event)
{
    if(toolType == DRAW)
    {
        ui->graphicsView->setCursor(Qt::CrossCursor);
        Shape *rect  = new Shape(layerType);
        rect->setMyScale(1/this->scale);
        scene->addItem(rect);
        rect->setPos(event->scenePos());
        toolType = SELECT;
        ui->graphicsView->unsetCursor();
    }
}

void MainWindow::setScale(qreal scale)
{
    this->scale*=scale;

    ui->graphicsView->scale(scale,scale);

    foreach(QGraphicsItem* item, scene->items())
        ((Shape*)item)->setMyScale(1/scale);
}

void MainWindow::on_actionZoon_In_triggered()
{
    this->setScale(1.25);
}

void MainWindow::on_actionZoon_Out_triggered()
{
    this->setScale(0.8);
}

void MainWindow::on_toolButton_released()
{
    toolType = DRAW;
    layerType = METAL1;
}
void MainWindow::on_toolButton_2_released()
{
    toolType = DRAW;
    layerType = METAL2;
}

void MainWindow::on_toolButton_3_released()
{
    toolType = DRAW;
    layerType = DIFF;
}

void MainWindow::on_toolButton_7_released()
{
    toolType = DRAW;
    layerType = P1;
}

void MainWindow::on_toolButton_4_released()
{
    toolType = DRAW;
    layerType = NTUB;
}

void MainWindow::on_toolButton_5_released()
{
    toolType = DRAW;
    layerType = PPLUS;
}

void MainWindow::on_toolButton_6_released()
{
    toolType = DRAW;
    layerType = NPLUS;
}

void MainWindow::on_toolButton_8_released()
{
    toolType = DRAW;
    layerType = CONT;
}

void MainWindow::on_actionDelete_triggered()
{
    foreach(QGraphicsItem* item, scene->selectedItems())
        scene->removeItem(item);
}

void MainWindow::on_actionSelect_Under_Object_triggered()
{
    selectUnder();
}

void MainWindow::selectUnder()
{
    QGraphicsItem* item = scene->selectedItems().first();

    foreach(QGraphicsItem* i, item->collidingItems())
        if(((Shape*)i)->type == ((Shape*)item)->type)
            i->zValue() <= item->zValue() ? item->setZValue(i->zValue() -0.001) : 0;
}


